
from configs import errorCode, config
from views import BaseHandler

from models import good_sku_detail

class GoodDetail(BaseHandler):

    async def get(self, id):
        """
        ---
        tags:
          - 商品详情
        summary:
        description:
        parameters:
          - name: spu商品的id
            in: path
            description: spu商品的id
            required: true
            schema:
              type: string
        responses:
          '200':
            description: successful operation
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/OkModel'
          '400':
            description: error operation
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/ErrorModel'
        """
        # 查出good_spu的所有字段信息
        spu = await good_sku_detail.get_spu_info(id)
        if not spu:
            return self.write_error(errorCode.NOT_GOODS, '商品不存在')

        # 查询spu商品是否收藏
        is_collect = await good_sku_detail.query_spu_is_collect(id)

        # 根据二级分类的id找出一级分类的id

        # 根据good_spu的id 查出在它之下的所有sku_id
        sku_id_list = await good_sku_detail.get_sku_from_spu(id)
        if not sku_id_list:
            return self.write_error(errorCode.NOT_GOODS, '商品不存在')

        # 根据一级分类的id查出property对应的id和名称
        new_sku_id_list = []
        for i in sku_id_list:
            new_sku_id_list.append(i['id'])

        # 根据当前spu下所有的sku_id查出所有的属性key和属性值
        property_val_list = await good_sku_detail.get_property_from_sku(new_sku_id_list)
        if not property_val_list:
            return self.write_error(errorCode.NOT_GOODS, '商品不存在')

        # 构造成属性key value 字典 并去重值value
        new_property = {}
        for i in property_val_list:
            new_property.setdefault(i['property_id'], []).append(i['title'])
            new_property[i['property_id']] = list(set(new_property[i['property_id']]))

        # 获取property的title
        property_id_list = list(new_property.keys())
        property_list = await good_sku_detail.get_property_title_form_id(property_id_list)

        new_property_val = {}
        for i in property_list:
           new_property_val[i['title']] = new_property.get(i['id'])
        self.response_data(spu, new_property_val, is_collect)

    def response_data(self, spu, new_property_val, is_collect):
        spu[0]['property'] = list(new_property_val.items())
        spu[0]['price'] = float(spu[0]['price'])
        spu[0]['img'] = config.IMG_PATH + spu[0]['img']
        spu[0]['is_collect'] = is_collect
        return self.write_json(data=spu[0])

